<?php

/**
 * home actions.
 *
 * @package    M2M
 * @subpackage home
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class homeActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    //$this->forward('default', 'module');

  }

  public function executeSubmitPresentationRequest(sfWebRequest $request)
  {
    $this->forward404Unless($email = $request->getPostParameter('request_email'));

    $v = new sfValidatorEmail();
    try {
      $email = $v->clean($email);
    } catch (sfValidatorError $e) {
      return $this->renderText($e);
    }

    $existingEmail = $this->checkDuplicateEmail($email);

    if($existingEmail) {
      return $this->renderText('Email already exists.');
    }
    else {
      $pd = new PresentationDownloads();
      $pd->setEmail($email);
      $pd->save();
      $successMsg = 'Registration success.';
      return $this->renderText($successMsg);
    }

  }

  public function executeSubmitBooking(sfWebRequest $request)
  {
    $this->forward404Unless($bookingFormParameters = $request->getPostParameters());

    $validationResult = $this->validateBookingForm($bookingFormParameters);

    if($validationResult['type'] == 'Success') {

      $b = new Bookings();
      $b->setName($bookingFormParameters['name']);
      $b->setEmail($bookingFormParameters['email']);
      $b->setCompany($bookingFormParameters['company']);
      $b->setMobileNumber($bookingFormParameters['mobile_number']);
      $bookingFormParameters['schedule_time'] = date('Y-m-d H:i:s',strtotime($bookingFormParameters['demo']['year'].'-'.$bookingFormParameters['demo']['month'].'-'.$bookingFormParameters['demo']['day'].' '.$bookingFormParameters['demo']['hour'].':'.$bookingFormParameters['demo']['minute'].' '.$bookingFormParameters['demo']['period']));
      $b->setSchedule($bookingFormParameters['schedule_time']);
      $bookingFormParameters['contact_time'] = date('H:i',strtotime($bookingFormParameters['contact']['hour'].':'.$bookingFormParameters['contact']['minute'].' '.$bookingFormParameters['contact']['period']));
      $b->setContactTime($bookingFormParameters['contact_time']);
      $b->save();
      $sent = $this->sendToEmail($bookingFormParameters);
      $successMsg = ($sent) ? 'Registration success. You will be contacted in the next few days.' : 'An error occured while sending email.';
      return $this->renderText($successMsg);
    }
    else {
      return $this->renderText($validationResult['message']);
    }

    /*$existingEmail = Doctrine_Core::getTable('Bookings')->findOneByEmail($email);

    if($existingEmail) {
      return $this->renderText('Email already exists.');
    }
    else {

    }*/

  }

  public function executeCheckDuplicateEmail(sfWebRequest $request)
  {
    $this->forward404Unless($email = $request->getPostParameter('request_email'));

    $existingEmail = $this->checkDuplicateEmail($email);

    if($existingEmail) {
      return $this->renderText('false');
    }
    else {
      return $this->renderText('true');
    }
  }

  private function checkDuplicateEmail($email)
  {
    $existingEmail = Doctrine_Core::getTable('PresentationDownloads')->findOneByEmail($email);
    if($existingEmail) {
      return true;
    }
    else {
      return false;
    }
  }

  private function validateBookingForm($formData)
  {
    $result['type'] = 'Success';
    $result['message'] = '';

    // Check if name is empty
    if(empty($formData['name'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Name is empty';
    }

    // Check if email is empty and invalid
    if(empty($formData['email'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Email is empty';
    }
    else {
      $v = new sfValidatorEmail();
      try {
        $email = $v->clean($formData['email']);
      } catch (sfValidatorError $e) {
        $result['type'] = 'Error';
        $result['message'] = $e;
      }
    }

    // Check if company is empty
    if(empty($formData['company'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Company is empty';
    }

    // Check if mobile_number is empty or not digits
    if(empty($formData['mobile_number'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Mobile number is empty';
    }
    elseif(!ctype_digit($formData['mobile_number'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Invalid mobile number';
    }

    // Check if schedule is missing something
    if(empty($formData['demo']['month']) ||
            empty($formData['demo']['day']) ||
            empty($formData['demo']['year']) ||
            empty($formData['demo']['hour']) ||
            empty($formData['demo']['minute']) ||
            empty($formData['demo']['period'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Missing value in demo schedule';
    }

    // Check if contact time is missing something
    if(empty($formData['contact']['hour']) ||
            empty($formData['contact']['minute']) ||
            empty($formData['contact']['period'])) {
      $result['type'] = 'Error';
      $result['message'] = 'Missing value in contact time';
    }

    return $result;

  }

  private function sendToEmail($formValues)
  {
    $email = "zmramos@globetel.com.ph";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
    $headers .= 'From: negostaronline@globebusiness.com.ph' . "\r\n" .
        'Bcc: ssantiago@netbooster.com' . "\r\n" .
//        'Cc: Rommel Zamora <rommel.zamora@yellowasp.com>, Joelle Jacinto <zjbjacinto@globetel.com.ph> '. "\r\n" .
//        'Reply-To: salessupport@globetel.com.ph' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    unset($formValues['schedule_time'], $formValues['contact_time']);
    foreach($formValues as $key=>$val) {
      if($key == 'demo') {
        $data[] = "<li><b>".$key.":</b>&nbsp;".$val['month'].'/'.$val['day'].'/'.$val['year'].' '.$val['hour'].':'.$val['minute'].' '.$val['period'];
      }
      elseif($key == 'contact') {
        $data[] = "<li><b>".$key.":</b>&nbsp;".$val['hour'].':'.$val['minute'].' '.$val['period'];
      }
      else {
        $data[] = "<li><b>".$key.":</b>&nbsp;".$val."</li>";
      }
    }
    $data = "<html><body><ul>".implode("", $data)."</ul></body></html>";

    $sent = mail ( $email, "M2M Booking Email Test", $data, $headers);

    return $sent;
  }



}
